package StudyCode.summary.zipfile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ExtractsZIPArchiveTargetDirectory {
	protected static final int bufferSize = 1024;

	public static synchronized void extract(Path archive,
	                                        Path targetDirectory) throws Exception {
		System.out.println("解压中 " + archive.getFileName().toString() + "...");
		byte[] buffer = new byte[bufferSize];

		try (ZipInputStream zin = new ZipInputStream(new FileInputStream(
				archive.toFile()))) {
			ZipEntry ze;
			while ((ze = zin.getNextEntry()) != null) {
				Path extractedFile = targetDirectory.resolve(ze.getName());
				try (FileOutputStream fout = new FileOutputStream(
						extractedFile.toFile())) {

					int len;
					while ((len = zin.read(buffer)) > 0) {
						fout.write(buffer, 0, len);
					}

					zin.closeEntry();
				} catch (IOException ioe_inner) {
					ioe_inner.printStackTrace();
				}
			}
		} catch (IOException ioe_outter) {
			ioe_outter.printStackTrace();
		}
		System.out.println("解压 " + archive.getFileName().toString() + " 结束.");
	}
}
